package com.tensquare.gateway.service.impl;


import com.tensquare.gateway.service.RsaService;
import com.tensquare.rsa.Base64Utils;
import com.tensquare.rsa.RSA;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;



/**
 * RSA 加解密
 *
 * @author Administrator
 */
@Service("RsaService")
public class RsaServiceImpl implements RsaService {

    /***
     * RSA解密
     */
    public String RSADecryptDataPEM(String encryptData, String prvKey) throws Exception {
    	byte[] encryptBytes = encryptData.getBytes();
        byte[] prvdata = RSA.decryptByPrivateKey(Base64Utils.decode(encryptData), prvKey);

        return new String(prvdata, StandardCharsets.UTF_8);
    }

    @Override
	public String RSADecryptDataBytes(byte[] encryptBytes, String prvKey)
			throws Exception {
		// TODO Auto-generated method stub
    	byte[] prvdata = RSA.decryptByPrivateKey(encryptBytes, prvKey);
        return new String(prvdata, StandardCharsets.UTF_8);
	}

    /***
     * RSA加密
     */
    public String RSAEncryptDataPEM(String data, String pubKey) throws Exception {

        byte[] pubdata = RSA.encryptByPublicKey(data.getBytes(StandardCharsets.UTF_8), pubKey);
        return Base64Utils.encode(pubdata);

    }

	@Override
	public String getRsaAlgorithm() {
		// TODO Auto-generated method stub
		KeyFactory keyFactory;
		try {
			keyFactory = KeyFactory.getInstance("RSA");
            return keyFactory.getAlgorithm();
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}


}
